<script setup lang="ts">
import * as echarts from 'echarts';
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import {
  panChartData,
  moneyTreeChartData,
  countTreeChartData,
  getData
} from '@/components/Store/useChartDataStore';

// 饼图相关
let panChart: echarts.ECharts | null = null;
const panData = ref([
  { value: 0, name: '售出' },
  { value: 0, name: '购入' },
  { value: 0, name: '划拨' }
]);

// 金额柱状图相关
let moneyBarChart: echarts.ECharts | null = null;
const moneyBarData = ref<{ name: string; outValue: number; inValue: number }[]>([]);

// 数量柱状图相关
let countBarChart: echarts.ECharts | null = null;
const countBarData = ref<{ name: string; outValue: number; inValue: number }[]>([]);

// 数据加载状态
const dataLoading = ref(true);
const initialized = ref(false);

function getYesterdayRange() {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const yesterdayStart = new Date(today);
  yesterdayStart.setDate(today.getDate() - 1);
  const yesterdayEnd = new Date(today);
  yesterdayEnd.setHours(23, 59, 59, 999);
  return { yesterdayStart, yesterdayEnd };
}

onMounted(async () => {
  // 初始化所有图表实例
  await initCharts();

  initialized.value = true;

  // 添加resize监听器
  window.addEventListener('resize', resizeCharts);
});

onUnmounted(() => {
  // 清理所有图表实例
  disposeChart(panChart);
  disposeChart(moneyBarChart);
  disposeChart(countBarChart);

  // 移除resize监听器
  window.removeEventListener('resize', resizeCharts);
});

// 监听数据变化
watch(panChartData, updatePanChartData);
watch(moneyTreeChartData, updateMoneyBarData);
watch(countTreeChartData, updateCountBarData);

// 初始化图表
async function initCharts() {
  const panChartDom = document.getElementById("panChart");
  if (panChartDom) panChart = echarts.init(panChartDom);

  const moneyBarDom = document.getElementById("moneyBarChart");
  if (moneyBarDom) moneyBarChart = echarts.init(moneyBarDom);

  const countBarDom = document.getElementById("countBarChart");
  if (countBarDom) countBarChart = echarts.init(countBarDom);

  // 加载数据并更新图表
  await loadDataAndUpdate();
}

// 辅助函数 - 清理图表
function disposeChart(chart: echarts.ECharts | null) {
  if (chart) {
    chart.dispose();
    chart = null;
  }
}

// 辅助函数 - 调整所有图表尺寸
function resizeCharts() {
  panChart?.resize();
  moneyBarChart?.resize();
  countBarChart?.resize();
}

async function loadDataAndUpdate() {
  dataLoading.value = true;
  try {
    await getData();
    updateAllChartsData();
  } finally {
    dataLoading.value = false;
  }
}

function updateAllChartsData() {
  updatePanChartData();
  updateMoneyBarData();
  updateCountBarData();
}

// 更新饼图数据
function updatePanChartData() {
  if (!panChart || !initialized.value) return;

  // 重置数据
  panData.value = [
    { value: 0, name: '售出' },
    { value: 0, name: '购入' },
    { value: 0, name: '划拨' }
  ];

  // 检查是否有数据
  if (!panChartData.value || panChartData.value.length === 0) {
    showNoDataIndicator(panChart, '订单类型饼图');
    return;
  }

  const { yesterdayStart, yesterdayEnd } = getYesterdayRange();

  // 统计数据
  panChartData.value.forEach(item => {
    const itemTime = new Date(item.dealTime).getTime();
    if (itemTime >= yesterdayStart.getTime() && itemTime < yesterdayEnd.getTime()) {
      if (item.name === "售出") panData.value[0].value += 1;
      else if (item.name === "购入") panData.value[1].value += 1;
      else if (item.name === "划拨") panData.value[2].value += 1;
    }
  });



  // 过滤掉值为0的项
  const filteredData = panData.value.filter(item => item.value > 0);

  // 如果没有有效数据，显示提示
  if (filteredData.length === 0) {
    showNoDataIndicator(panChart, '订单类型饼图');
    return;
  }

  // 配置项
  const option = {
    title: {
      text: '订单类型饼图',
      left: 'center',
      top: '2%'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0,
      data: filteredData.map(item => item.name)
    },
    series: [
      {
        name: '订单类型',
        type: 'pie',
        radius: '55%',
        center: ['50%', '45%'],
        data: filteredData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  panChart.setOption(option);
}

// 更新金额柱状图
function updateMoneyBarData() {
  if (!moneyBarChart || !initialized.value) return;

  moneyBarData.value = [];

  // 检查是否有数据
  if (!moneyTreeChartData.value || moneyTreeChartData.value.length === 0) {
    showNoDataIndicator(moneyBarChart, '货物交易金额');
    return;
  }

  const { yesterdayStart, yesterdayEnd } = getYesterdayRange();

  // 按货物名称分组
  const goodsMap = new Map<string, { outValue: number; inValue: number }>();

  moneyTreeChartData.value.forEach(item => {
    const itemTime = new Date(item.dealTime).getTime();
    if (itemTime >= yesterdayStart.getTime() && itemTime < yesterdayEnd.getTime()) {
      if (!goodsMap.has(item.name)) {
        goodsMap.set(item.name, { outValue: 0, inValue: 0 });
      }

      const goodsData = goodsMap.get(item.name)!;
      goodsData.outValue += item.outValue;
      goodsData.inValue += item.inValue;
    }
  });

  // 转换为数组并过滤掉没有数据的商品
  moneyBarData.value = Array.from(goodsMap.entries())
      .map(([name, values]) => ({ name, ...values }))
      .filter(item => item.outValue > 0 || item.inValue > 0);

  // 按总金额排序
  moneyBarData.value.sort((a, b) => (b.outValue + b.inValue) - (a.outValue + a.inValue));

  // 如果没有有效数据，显示提示
  if (moneyBarData.value.length === 0) {
    showNoDataIndicator(moneyBarChart, '货物交易金额');
    return;
  }

  // 配置项
  const option = {
    title: {
      text: '货物交易金额',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params: any) {
        const data = params[0];
        const sellData = params[1] || { value: 0 };
        return `
          ${data.name}<br/>
          购入金额: ${sellData.value}元<br/>
          售出金额: ${data.value}元
        `;
      }
    },
    legend: {
      data: ['售出金额', '购入金额'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: moneyBarData.value.map(item => item.name)
    },
    yAxis: {
      type: 'value',
      name: '金额（元）'
    },
    series: [
      {
        name: '售出金额',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: moneyBarData.value.map(item => item.outValue),
        itemStyle: {
          color: '#5470c6'
        }
      },
      {
        name: '购入金额',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: moneyBarData.value.map(item => item.inValue),
        itemStyle: {
          color: '#91cc75'
        }
      }
    ]
  };

  moneyBarChart.setOption(option);
}

// 更新数量柱状图
function updateCountBarData() {
  if (!countBarChart || !initialized.value) return;

  countBarData.value = [];

  // 检查是否有数据
  if (!countTreeChartData.value || countTreeChartData.value.length === 0) {
    showNoDataIndicator(countBarChart, '货物交易数量');
    return;
  }

  const { yesterdayStart, yesterdayEnd } = getYesterdayRange();

  // 按货物名称分组
  const goodsMap = new Map<string, { outValue: number; inValue: number }>();

  countTreeChartData.value.forEach(item => {
    const itemTime = new Date(item.dealTime).getTime();
    if (itemTime >= yesterdayStart.getTime() && itemTime < yesterdayEnd.getTime()) {
      if (!goodsMap.has(item.name)) {
        goodsMap.set(item.name, { outValue: 0, inValue: 0 });
      }

      const goodsData = goodsMap.get(item.name)!;
      goodsData.outValue += item.outValue;
      goodsData.inValue += item.inValue;
    }
  });

  // 转换为数组并过滤掉没有数据的商品
  countBarData.value = Array.from(goodsMap.entries())
      .map(([name, values]) => ({ name, ...values }))
      .filter(item => item.outValue > 0 || item.inValue > 0);

  // 按总数量排序
  countBarData.value.sort((a, b) => (b.outValue + b.inValue) - (a.outValue + a.inValue));

  // 如果没有有效数据，显示提示
  if (countBarData.value.length === 0) {
    showNoDataIndicator(countBarChart, '货物交易数量');
    return;
  }

  // 配置项
  const option = {
    title: {
      text: '货物交易数量',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params: any) {
        const data = params[0];
        const sellData = params[1] || { value: 0 };
        return `
          ${data.name}<br/>
          购入数量: ${sellData.value}件<br/>
          售出数量: ${data.value}件
        `;
      }
    },
    legend: {
      data: ['售出数量', '购入数量'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: countBarData.value.map(item => item.name)
    },
    yAxis: {
      type: 'value',
      name: '数量（件）'
    },
    series: [
      {
        name: '售出数量',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        data: countBarData.value.map(item => item.outValue),
        itemStyle: {
          color: '#5470c6'
        }
      },
      {
        name: '购入数量',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        data: countBarData.value.map(item => item.inValue),
        itemStyle: {
          color: '#91cc75'
        }
      }
    ]
  };

  countBarChart.setOption(option);
}

// 显示无数据提示
function showNoDataIndicator(chart: echarts.ECharts | null, title: string) {
  if (!chart) return;

  chart.setOption({
    title: {
      text: title,
      subtext: '暂无数据',
      left: 'center',
      top: 'center',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold'
      },
      subtextStyle: {
        fontSize: 14,
        color: '#999'
      }
    },
    series: [] // 清空系列数据
  });
}

// 强制刷新所有图表
function forceRefreshCharts() {
  // 若对象存在，则销毁
  if (panChart) panChart.dispose();
  if (moneyBarChart) moneyBarChart.dispose();
  if (countBarChart) countBarChart.dispose();

  initialized.value = false;

  nextTick(async () => {//nextTick 函数，用于在 DOM 更新完成后执行异步操作。
    await initCharts();
    initialized.value = true;
  });
}
</script>

<template>
  <div class="dashboard">
    <div class="header">
      <h1>交易日报表</h1>
      <p>显示前一天（{{ new Date(new Date().setDate(new Date().getDate() - 1)).toLocaleDateString() }}）的交易数据</p>
      <button class="refresh-btn" @click="forceRefreshCharts">
        <i class="icon-refresh"></i> 刷新图表
      </button>
    </div>

    <div class="chartsContainer">
      <!-- 饼图单独一行 -->
      <div class="row">
        <div class="chart-item">
          <div v-if="dataLoading" class="chart-loading">
            <div class="loader"></div>
            数据加载中...
          </div>
          <div id="panChart" style="width: 100%; height: 400px"></div>
        </div>
      </div>

      <!-- 第二行：两个柱状图 -->
      <div class="row">
        <div class="chart-item">
          <div v-if="dataLoading" class="chart-loading">
            <div class="loader"></div>
            数据加载中...
          </div>
          <div id="moneyBarChart" style="width: 100%; height: 400px"></div>
        </div>

        <div class="chart-item">
          <div v-if="dataLoading" class="chart-loading">
            <div class="loader"></div>
            数据加载中...
          </div>
          <div id="countBarChart" style="width: 100%; height: 400px"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.dashboard {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  position: relative;
}

.header h1 {
  margin: 0;
  font-size: 2.2rem;
  font-weight: 700;
}

.header p {
  margin: 10px 0 0;
  font-size: 1.1rem;
  opacity: 0.9;
}

.refresh-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  padding: 8px 15px;
  background-color: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 20px;
  color: white;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 5px;
}

.refresh-btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

.chartsContainer {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.row {
  display: flex;
  gap: 25px;
}

.chart-item {
  flex: 1;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  padding: 20px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  min-height: 350px;
}

.chart-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
}

.chart-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.9);
  z-index: 10;
  font-size: 18px;
  color: #555;
  border-radius: 12px;
}

.loader {
  border: 5px solid #f3f3f3;
  border-top: 5px solid #3498db;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  animation: spin 1.5s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@media (max-width: 992px) {
  .row {
    flex-direction: column;
  }

  .chart-item {
    width: 100%;
  }
}
</style>